import threading, time



class TestThread:

    def __init__(self):
        # 创建线程锁
        self.lock = threading.Lock()
        # 日志文件名
        self.log_filename = 'activity.log'

    def _write_log(self, activity):
        """线程安全的日志写入方法"""
        timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
        log_entry = f'[{timestamp} {activity}]\n'

        try:
            # 获取锁确保线程安全
            with self.lock:
                with open(self.log_filename, 'a', encoding='utf-8') as f:
                    f.write(log_entry)
        except Exception as e:
            print(f'写入日志失败：{e}')

    def watch_tv(self):
        start_time = time.time()
        # print(f'开始时间：{start_time}')
        time.sleep(3)
        self._write_log('看电视任务完成')
        return time.time() - start_time

    def do_homework(self):
        start_time = time.time()
        # print(f'开始时间：{start_time}')
        time.sleep(5)
        self._write_log('做作业任务完成')
        return time.time() - start_time

    def im_byqq(self):
        start_time = time.time()
        # print(f'开始时间：{start_time}')
        time.sleep(4)
        self._write_log('QQ聊天任务完成')
        return time.time() - start_time


if __name__ == '__main__':
    # 创建测试对象
    tester = TestThread()

    print('=== 串行执行 ===')
    tv_time = tester.watch_tv()
    print(f'看电视执行时间：{tv_time:.2f}秒')

    hw_time = tester.do_homework()
    print(f'做作业执行时间：{hw_time:.2f}秒')

    qq_time = tester.im_byqq()
    print(f'QQ聊天执行时间：{qq_time:.2f}秒')

    total_serial = tv_time + hw_time + qq_time
    print(f'串行总时间：{total_serial:.2f}秒\n')

    print('=== 多线程执行 ===')
    start = time.time()
    # print(f'多线程执行开始时间：{start}')

    # 创建线程
    tv_thread = threading.Thread(target=tester.watch_tv)
    hw_thread = threading.Thread(target=tester.do_homework)
    qq_thread = threading.Thread(target=tester.im_byqq)

    # 启动线程
    tv_thread.start()
    hw_thread.start()
    qq_thread.start()

    # 等待所有线程完成
    tv_thread.join()
    hw_thread.join()
    qq_thread.join()

    total_parallel = time.time() - start
    print(f'多线程执行总时间：{total_parallel:.2f}秒')
    print(f'时间节省时间：{total_serial - total_parallel:.2f}秒')

    # 显示日志内容
    try:
        with open('activity.log', 'r', encoding='utf-8') as f:
            print('\n=== 日志内容 ===')
            print(f.read())
    except Exception as e:
        print(f'读取日志失败：{e}')



